﻿using AzureLogManager.Log;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Diagnostics;
using System.Threading;

namespace AzureLogManager.Azure.Sample.API
{
    public class SampleService : ISampleService
    {
        public SampleService()
        {
            #region - Table storage -

            // Retrieve the storage account from the connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageAccount"));

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            CloudTable table = tableClient.GetTableReference("logs");
            table.CreateIfNotExists();

            String logType = CloudConfigurationManager.GetSetting("LogType");

            LogManager.Table = table;
            LogManager.LogType = logType;

            #endregion

            RoleEnvironment.Changing += RoleEnvironment_Changing;
        }

        /// <summary>
        /// Take into account configuration modification
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void RoleEnvironment_Changing(object sender, RoleEnvironmentChangingEventArgs e)
        {
            String logType = CloudConfigurationManager.GetSetting("LogType");

            LogManager.LogType = logType;
        }

        public String GetHelloWorld()
        {
            Stopwatch sw = Stopwatch.StartNew();
            Boolean hasError = false;

            try
            {
                Thread.Sleep(2000);
            }
            catch (Exception ex)
            {
                hasError = true;
                LogManager.Log(LogEntity.LogType.Error, 0, ex.ToString());
            }
            finally
            {
                sw.Stop();
                if (hasError == false)
                {
                    LogManager.Log(LogEntity.LogType.Message, sw.ElapsedMilliseconds);
                }
            }

            return "Hello World";
        }

        public void GetNotImplementedException()
        {
            try
            {
                throw new NotImplementedException();
            }
            catch (Exception ex)
            {
                LogManager.Log(LogEntity.LogType.Error, 0, ex.ToString());
            }
        }
    }
}
